import { makeAutoObservable } from 'mobx';
import * as api from './api';
import { MAGIC_NUMBERS } from './definitions';

const { DRIVER_STATE } = MAGIC_NUMBERS;

class TableArgs {
  constructor(query) {
    this._args = {
      search: {},
      pg: {
        page: 0,
        sort: ['departureTime;desc', 'crDate;desc'],
        size: 10,
      },
    };
    this.loading = false;
    this.total = 0;
    this.dataSource = [];
    this.query = query;
    makeAutoObservable(this, {});
  }
  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}

export default class ScTaskStore {
  loadingLogs = false;
  loadingOrderLogs = false;

  _mainArgs = new TableArgs(this.query);
  _sendCarArgs = new TableArgs(this.querySendCarData);

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.dataSource = yield api.search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  /**
   * @func 获取派车表格数据
   * @desc
   * @param {}
   */
  * querySendCarData(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.countSendCars(search);
      this.dataSource = yield api.searchSendCars(search, pg);
    } finally {
      this.loading = false;
    }
  }

  /**
   * @func 获取订单数据
   * @desc 根据订单id获取订单数据
   * @param {string} orderId 订单id
   * @return {object} 订单数据
   */
  * getOrderInfo(orderId) {
    return yield api.get(orderId);
  }

  /**
   * @func 获取任务日志数据
   * @desc
   * @param {object} task 任务数据
   * @return {}
   */
  * getLogs(task) {
    const { driverInfo = [], id } = task || {};
    const workIdsOnlyOne = [...new Set(driverInfo.map(({ number }) => number))];
    const search = {
      targetIds: [...workIdsOnlyOne, id],
    };
    this.loadingLogs = true;
    try {
      return yield api.getLogs(search);
    } finally {
      this.loadingLogs = false;
    }
  }

  /**
   * @func 获取订单任务日志数据
   * @desc
   * @param {}
   * @return {}
   */
  * getOrderLogs(order) {
    const { taskIds: taskIdsTmp = [], id } = order;
    const taskIds = [...new Set(taskIdsTmp)];
    const orderSearch = {
      targetType: 'scOrder',
      targetIds: [...taskIds, id],
    };
    this.loadingOrderLogs = true;
    try {
      const orderLogs = yield api.getLogs(orderSearch);
      const taskLogs = [];
      for (const taskId of taskIds) {
        const taskInfo = yield api.getTaskInfo(taskId);
        const { driverInfo = [], carrierCompanyName, tickets = [] } = toJS(taskInfo);
        // 获取任务涉及的工单id
        const workOrderIds = driverInfo.reduce((res, cur) => {
          const { number } = cur;
          res.push(number);
          return res;
        }, []);

        const taskSearch = {
          targetIds: [...workOrderIds, taskId],
        };
        const taskLogsRes = yield api.getLogs(taskSearch);
        taskLogs.push({
          taskId,
          taskLog: toJS(taskLogsRes),
          companyName: carrierCompanyName,
          tickets,
        });
      }
      return { orderLogs, taskLogs };
    } finally {
      this.loadingOrderLogs = false;
    }
  }

  * getCompany(companyId) {
    return yield api.getCompany(companyId);
  }

  * company(args) {
    const res = yield api.company(args);
    return res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  * update(task) {
    yield api.update(task);
    this._mainArgs.query();
  }

  * updatePrice(data) {
    yield api.updatePrice(data);
    this._mainArgs.query();
  }

  * alterationCompany(data) {
    yield api.alterationCompany(data);
    this._mainArgs.query();
  }

  * sendCar(data) {
    yield api.sendCar(data);
    this._mainArgs.query();
  }

  * cancelSendCar(data) {
    yield api.cancelSendCar(data);
    this._mainArgs.query();
  }

  * finishTask(taskId) {
    yield api.updateTaskState(taskId);
    this._mainArgs.query();
  }

  getDriverInfo(driverInfo = []) {
    if (driverInfo.length <= 0) return {};
    const curDriver = driverInfo.find((e) => e.state !== DRIVER_STATE.CANCEL);
    return curDriver;
  }

  /**
   * @func 修改任务状态
   * @desc
   * @param {string} taskId 任务id
   * @param {string} state  需要变更为的状态
   */
  async changeTaskState(taskId, state) {
    const param = {
      state,
      flag: DRIVER_STATE.FINISH !== state,
    };
    await api.changeTaskState(taskId, param);
  }
}
